/*
 * @Author: 郑刘利
 * @Date: 2020-03-10 18:00:25
 * @LastEditors: 郑刘利
 * @LastEditTime: 2020-03-18 17:01:29
 * @Description:
 * @FilePath: \one_project\src\lib\Player\index.ts
 */
export class Player {
    private static _instance?: Player;
    public static get instance() {
        if (!this._instance) {
            this._instance = new Player();
        }
        return this._instance;
    }
    private media!: HTMLAudioElement;
    private mediaList: string[] = [];
    private index = -1;
    private constructor() {
        this.media = document.createElement('audio');
    }
    public next() {
        if (this.mediaList.length === 0) {
            this.index = -1;
            return;
        }
        this.index++;
        if (this.index === this.mediaList.length) {
            this.index = 0;
        }
        this.refresh();
    }
    public prev() {
        if (this.mediaList.length === 0) {
            this.index = -1;
            return;
        }
        this.index--;
        if (this.index === -1) {
            this.index = this.mediaList.length - 1;
        }
        this.refresh();
    }
    public play() {
        this.media.play();
    }
    public pause() {
        this.media.pause();
    }

    public setMediaList(list: string[]) {
        this.mediaList = list;
    }
    public get paused() {
        return this.media.paused || false;
    }
    private refresh() {
        this.media.src = this.getSrc();
    }
    private getSrc() {
        if (this.mediaList.length === 0) {
            return '';
        }
        return this.mediaList[this.index];
    }
}
